﻿using Admin.ApplicationLib.Entities;
using Admin.CommonLib.Models.User;
using Ardalis.Specification.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System.Linq;

namespace Admin.ApplicationLib.Repositories
{
    public class UserRepository : RepositoryBase<UserEntity>, IUserRepository
    {
        private readonly AdminApplicationDbContext _dbContext;

        public UserRepository(AdminApplicationDbContext dbContext) : base(dbContext)
        {
            _dbContext = dbContext;
        }

        public override Task DeleteAsync(UserEntity entity, CancellationToken cancellationToken = new CancellationToken())
        {
            entity.DataState = 0;
            return base.UpdateAsync(entity, cancellationToken);
        }

        public async Task<Tuple<IList<UserEntity>, int>> QueryByPageRoleAsync(Guid id, UserSearchRequestDto model)
        {
            var queryable = (from users in _dbContext.Users
                join userRole in _dbContext.UserRoles! on users.Id equals userRole.UserId
                where userRole.RoleId == id
                select users);

            // var totalCount = await queryable.CountAsync();

            var totalCount = 0;

            if (model.Page > 0)
            {
                queryable = queryable.Skip((model.Page - 1) * model.Limit);
            }

            if (model.Limit > 0)
            {
                queryable = queryable.Take(model.Limit);
            }

            IList<UserEntity> userEntities = await queryable.ToListAsync();

            return new Tuple<IList<UserEntity>, int>(userEntities, totalCount);
        }

        public async Task<IList<UserEntity>> QueryByIdsAsync(List<Guid> model)
        {
            return await _dbContext.Users.Where(i => model.Contains(i.Id)).ToListAsync();
        }

        public async Task<IList<UserEntity>> QueryByRoleAsync(Guid roleId)
        {
            return await (from users in _dbContext.Users
                join userRole in _dbContext.UserRoles! on users.Id equals userRole.UserId
                where userRole.RoleId == roleId
                select users).ToListAsync();
        }

        public async Task<IList<UserEntity>> QueryByUserNamesAsync(List<string> model)
        {
            return await _dbContext.Users.Where(i => model.Contains(i.UserName)).ToListAsync();
        }
    }
}